package com.xujl.fastlib.window;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;

import com.xujl.fastlib.R;
import com.xujl.task.RxExecutor;
import com.xujl.task.RxHelper;
import com.xujl.task.RxLife;
import com.xujl.task.RxLifeList;

import razerdp.basepopup.BasePopupWindow;

public class LoadingWindow extends BasePopupWindow {
    private long lastShowTime;
    private static final int ACTION_SHOW = 1;
    private static final int ACTION_HIDE = 2;
    private int lastAction;
    private RxLifeList mRxLifeList = new RxLifeList();

    public LoadingWindow (Context context) {
        super(context);
        Activity activity = getContext();
        if (activity == null) {
            return;
        }
//        PopupBlurOption option = null;
//        option = new PopupBlurOption();
//        option.setFullScreen(true)
//                .setBlurRadius(5f)
//                .setBlurInDuration(-1)
//                .setBlurOutDuration(-1);
//        View decorView = activity.findViewById(android.R.id.content);
//        if (decorView instanceof ViewGroup && decorView.getId() == android.R.id.content) {
//            option.setBlurView(((ViewGroup) activity.getWindow().getDecorView()).getChildAt(0));
//            option.setFullScreen(true);
//        } else {
//            option.setBlurView(decorView);
//        }
//        setBlurOption(option);
        setBackground(Color.TRANSPARENT);
        setPopupGravity(Gravity.CENTER);
        setOutSideDismiss(false);
    }

    @Override
    public View onCreateContentView () {
        return createPopupById(R.layout.base_loading_window);
    }

    @Override
    public void showPopupWindow () {
        mRxLifeList.onDestroy();
        if (System.currentTimeMillis() - lastShowTime < 800 || lastAction != ACTION_SHOW) {
            lastShowTime = System.currentTimeMillis();
            lastAction = ACTION_SHOW;
            super.showPopupWindow();
        }

    }

    @Override
    public void dismiss () {
        BasePopupWindow parent = this;
        //加载显示不足一秒时，一秒后在关闭
        if (System.currentTimeMillis() - lastShowTime < 800) {
            RxExecutor.getInstance()
                    .executeTask(new RxHelper.DelayTask(800) {
                        @Override
                        public void timeOver () {
                            lastAction = ACTION_HIDE;
                            parent.dismiss();
                        }

                        @Override
                        public void bindLife (RxLife rxLife) {
                            super.bindLife(rxLife);
                            mRxLifeList.add(rxLife);
                        }
                    });
        } else {
            super.dismiss();
            lastAction = ACTION_HIDE;
        }
    }

    public void recycle () {
        mRxLifeList.onDestroy();
        super.dismiss();
    }
}

